import os
from JsonDB import JsonDB
from Menu import Menu
import pyperclip


class Application():
    CHECK_SOFTWARE_EXIST = True
    '检查软件是否存在'
    OPTIMIZE_PATH = False
    '优化快捷键路径'
    USE_CLIP_BOARD = True
    '使用剪切板'

    def __init__(self):
        source = 'source.ini'
        dist = 'dist.ini'

        try:
            self._loadConfig()

            assert os.path.exists(source), '路径[%s]不存在' % source
            assert os.path.isfile(source), '[%s]不是文件' % source

            file = open(source, 'r', encoding='utf-8')
            str = file.read()
            file.close()

            root = Menu(content=str)

            print('检查配置中同级菜单快捷键是否重复...')
            errorInfo = root.checkMenuHotkey()
            if errorInfo != '':
                print(errorInfo)
                raise Exception('程序中止')

            if self.CHECK_SOFTWARE_EXIST:
                print('检查配置中所有软件路径是否存在...')
                errorInfo = root.checkExeExist()
                if errorInfo != '':
                    print('不存在的exe路径有：\n' + errorInfo)
                    raise Exception('程序中止')

            print('开始生成快捷键菜单路径...')
            root.generateHotkeyMenu()

            if self.OPTIMIZE_PATH:
                print('开始优化快捷键路径')
                root.optimizeMenuPath()

            print('开始排序...')
            root.sort()

            print('开始对菜单进行编号区分...')
            root.numberingMenus()

            print('开始生成配置文件...')
            ini = root.generateIni()

            if self.USE_CLIP_BOARD:
                pyperclip.copy(ini)

            file = open(dist, 'w', encoding='utf-8')
            file.write(ini)
            file.close()

        except Exception as e:
            print(e)
            raise e
        else:
            print('生成成功:%s' % dist)
        finally:
            os.system('pause')
        

    def _loadConfig(self):
        db = JsonDB('config.json')

        value = db.get('checkSoftwareExist')
        if value == None:
            db.set('checkSoftwareExist', self.CHECK_SOFTWARE_EXIST)
        else:
            self.CHECK_SOFTWARE_EXIST = value

        value = db.get('optimizePath')
        if value == None:
            db.set('optimizePath', self.OPTIMIZE_PATH)
        else:
            self.OPTIMIZE_PATH = value

        value = db.get('useClipBoard')
        if value == None:
            db.set('useClipBoard', self.USE_CLIP_BOARD)
        else:
            self.USE_CLIP_BOARD = value

        db.save()


Application()
